package com.example.mydy;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import com.example.mydy.adapter.InviteeAdapter;
import com.example.mydy.api.UserApi;
import com.example.mydy.model.InvitationResponse;
import com.example.mydy.model.InviteCodeResponse;
import com.example.mydy.model.Invitee;
import com.example.mydy.model.PromotionResponse;
import com.example.mydy.model.UserData;
import com.example.mydy.model.UserTaskStatus;
import com.example.mydy.utils.NetworkUtils;
import com.example.mydy.utils.SharedPreferenceUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class PromotionActivity extends AppCompatActivity {

    private TextView inviteCountTv, taskRewardTodayTv, subTaskRewardTv, userBalanceTv;
    private TextView firstLevelCompletedTv, secondLevelCompletedTv, thirdLevelCompletedTv;
    private TextView firstLevelTotalTv, secondLevelTotalTv, thirdLevelTotalTv;
    
    // 邀请码和链接相关控件
    private TextView tvInviteCode, tvInviteLink;
    private Button btnCopy, btnShare;
    private TextView tvFirstLevelCount, tvSecondLevelCount, tvThirdLevelCount, tvTotalCount;
    private RecyclerView recyclerView;
    private InviteeAdapter adapter;
    private List<Invitee> inviteeList = new ArrayList<>();
    
    private String username;
    private String userId;
    private UserApi userApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_promotion);

        initViews();
        userApi = NetworkUtils.getAuthenticatedUserApi(this);
        userId = SharedPreferenceUtils.getString(this, "user_id", "");
        username = NetworkUtils.getUsername();
        
        setupListeners();
        loadUserData();
        loadInviteData();
        setupNavigationBar();
    }

    private void initViews() {
        inviteCountTv = findViewById(R.id.inviteCount);
        taskRewardTodayTv = findViewById(R.id.taskRewardToday);
        subTaskRewardTv = findViewById(R.id.subTaskReward);
        userBalanceTv = findViewById(R.id.userBalance);

        firstLevelCompletedTv = findViewById(R.id.first_level_completed);
        secondLevelCompletedTv = findViewById(R.id.second_level_completed);
        thirdLevelCompletedTv = findViewById(R.id.third_level_completed);

        firstLevelTotalTv = findViewById(R.id.first_level_total);
        secondLevelTotalTv = findViewById(R.id.second_level_total);
        thirdLevelTotalTv = findViewById(R.id.third_level_total);

        // 初始化邀请码和链接相关控件
        tvInviteCode = findViewById(R.id.tv_invite_code);
        tvInviteLink = findViewById(R.id.tv_invite_link);
        btnCopy = findViewById(R.id.btn_copy);
        btnShare = findViewById(R.id.btn_share);
        tvFirstLevelCount = findViewById(R.id.tv_first_level_count);
        tvSecondLevelCount = findViewById(R.id.tv_second_level_count);
        tvThirdLevelCount = findViewById(R.id.tv_third_level_count);
        tvTotalCount = findViewById(R.id.tv_total_count);
        recyclerView = findViewById(R.id.recycler_view);

        // 设置RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new InviteeAdapter(this, inviteeList);
        recyclerView.setAdapter(adapter);
    }
    
    private void setupListeners() {
        // 复制按钮点击事件
        btnCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inviteCode = tvInviteCode.getText().toString();
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("邀请码", inviteCode);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(PromotionActivity.this, "邀请码已复制到剪贴板", Toast.LENGTH_SHORT).show();
            }
        });

        // 分享按钮点击事件
        btnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inviteLink = tvInviteLink.getText().toString();
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType("text/plain");
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, "邀请链接");
                shareIntent.putExtra(Intent.EXTRA_TEXT, "快来加入我吧！使用我的邀请链接注册：" + inviteLink);
                startActivity(Intent.createChooser(shareIntent, "分享到"));
            }
        });
    }

    private void loadUserData() {
        if (username == null || username.isEmpty()) {
            return;
        }

        userApi.getUserData(username).enqueue(new Callback<UserData>() {
            @Override
            public void onResponse(Call<UserData> call, Response<UserData> response) {
                if (response.isSuccessful() && response.body() != null) {
                    UserData userData = response.body();
                    updateUserInfo(userData);
                } else {
                    Toast.makeText(PromotionActivity.this, "获取用户数据失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<UserData> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(PromotionActivity.this, "获取用户数据失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void loadInviteData() {
        // 获取邀请码
        fetchInviteCode();
        
        // 获取邀请记录
        fetchInvitations();
    }

    private void fetchInviteCode() {
        Call<InviteCodeResponse> call = userApi.getInviteCode(userId);
        call.enqueue(new Callback<InviteCodeResponse>() {
            @Override
            public void onResponse(Call<InviteCodeResponse> call, Response<InviteCodeResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    InviteCodeResponse inviteCodeResponse = response.body();
                    tvInviteCode.setText(inviteCodeResponse.getInviteCode());
                    tvInviteLink.setText(NetworkUtils.getCurrentBaseUrl() + "/register?code=" + inviteCodeResponse.getInviteCode());
                } else {
                    Toast.makeText(PromotionActivity.this, "获取邀请码失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<InviteCodeResponse> call, Throwable t) {
                Toast.makeText(PromotionActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void fetchInvitations() {
        Call<InvitationResponse> call = userApi.getInvitations(userId);
        call.enqueue(new Callback<InvitationResponse>() {
            @Override
            public void onResponse(Call<InvitationResponse> call, Response<InvitationResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    InvitationResponse invitationResponse = response.body();
                    
                    // 更新统计数据
                    tvFirstLevelCount.setText(String.valueOf(invitationResponse.getFirstLevelCount()));
                    tvSecondLevelCount.setText(String.valueOf(invitationResponse.getSecondLevelCount()));
                    tvThirdLevelCount.setText(String.valueOf(invitationResponse.getThirdLevelCount()));
                    tvTotalCount.setText(String.valueOf(invitationResponse.getTotalCount()));
                    
                    // 更新列表数据
                    inviteeList.clear();
                    inviteeList.addAll(invitationResponse.getInvitees());
                    adapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(PromotionActivity.this, "获取邀请记录失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<InvitationResponse> call, Throwable t) {
                Toast.makeText(PromotionActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updateUserInfo(UserData userData) {
        inviteCountTv.setText(String.valueOf(userData.getInviteCount()));
        taskRewardTodayTv.setText(String.format("%.2f", userData.getTaskRewardToday()));
        subTaskRewardTv.setText(String.format("%.2f", userData.getSubTaskReward()));
        userBalanceTv.setText(String.format("%.2f", userData.getUserBalance()));
    }

    private void updateUserTaskStatus(List<UserTaskStatus> userTaskStatusList) {
        int firstLevelCompleted = 0;
        int secondLevelCompleted = 0;
        int thirdLevelCompleted = 0;

        int firstLevelTotal = 0;
        int secondLevelTotal = 0;
        int thirdLevelTotal = 0;

        for (UserTaskStatus status : userTaskStatusList) {
            if ("completed".equals(status.getStatus())) {
                switch (status.getUserNickname()) {
                    case "一级用户":
                        firstLevelCompleted++;
                        break;
                    case "二级用户":
                        secondLevelCompleted++;
                        break;
                    case "三级用户":
                        thirdLevelCompleted++;
                        break;
                }
            }

            switch (status.getNickname()) {
                case "一级用户":
                    firstLevelTotal++;
                    break;
                case "二级用户":
                    secondLevelTotal++;
                    break;
                case "三级用户":
                    thirdLevelTotal++;
                    break;
            }
        }

        firstLevelCompletedTv.setText(String.valueOf(firstLevelCompleted));
        secondLevelCompletedTv.setText(String.valueOf(secondLevelCompleted));
        thirdLevelCompletedTv.setText(String.valueOf(thirdLevelCompleted));

        firstLevelTotalTv.setText(String.valueOf(firstLevelTotal));
        secondLevelTotalTv.setText(String.valueOf(secondLevelTotal));
        thirdLevelTotalTv.setText(String.valueOf(thirdLevelTotal));
    }

    private void setupNavigationBar() {
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        // 设置选中项为推广
        bottomNavigationView.setSelectedItemId(R.id.nav_promotion);
        
        // 设置导航菜单项选择监听器
        bottomNavigationView.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.nav_home) {
                // 先设置选中项为首页，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_home);
                startActivity(new Intent(this, MainActivity.class));
                finish();
                return true;
            } else if (itemId == R.id.nav_advertisement) {
                // 先设置选中项为广告，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_advertisement);
                startActivity(new Intent(this, AdvertisementListActivity.class));
                finish();
                return true;
            } else if (itemId == R.id.nav_project) {
                // 先设置选中项为项目，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_project);
                startActivity(new Intent(this, ProjectActivity.class));
                finish();
                return true;
            } else if (itemId == R.id.nav_promotion) {
                // 当前页面，无需操作
                return true;
            } else if (itemId == R.id.nav_my) {
                // 先设置选中项为我的，然后再跳转
                bottomNavigationView.setSelectedItemId(R.id.nav_my);
                startActivity(new Intent(this, MyActivity.class));
                finish();
                return true;
            }
            return false;
        });
    }
}